package com.rc.saas.tenant.controller.transfer;

import com.rc.saas.tenant.base.TenantBaseController;
import com.rc.saas.tenant.common.constant.ShiroConstants;
import com.rc.saas.tenant.common.vo.TResponse;
import com.rc.saas.tenant.model.member.MemberAccount;
import com.rc.saas.tenant.model.member.MemberInfo;
import com.rc.saas.tenant.model.tenant.Tenant;
import com.rc.saas.tenant.model.tenant.TenantSetting;
import com.rc.saas.tenant.model.tenant.TenantUser;
import com.rc.saas.tenant.service.member.MemberAccountService;
import com.rc.saas.tenant.service.member.MemberInfoService;
import com.rc.saas.tenant.service.tenant.TenantService;
import com.rc.saas.tenant.service.tenant.TenantSettingService;
import com.rc.saas.tenant.service.transfer.TransferOrderService;
import com.rc.saas.tenant.service.weixin.WxPayWalletService;
import com.rc.saas.tenant.transfers.weixin.WxTransPayWalletVo;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * 微信企业付款到零钱
 * https://pay.weixin.qq.com/wiki/doc/api/tools/mch_pay.php?chapter=14_1
 * Created by Sven on 2021/08/11
 */
@Controller
@Scope("prototype")
@RequestMapping(value = "/wxpay/transfer")
public class WeixinTransferController extends TenantBaseController {
    private static Logger logger = LogManager.getLogger(WeixinTransferController.class);

    @Autowired
    private TenantService tenantService;

    @Autowired
    private MemberInfoService memberInfoService;

    @Autowired
    private MemberAccountService memberAccountService;

    @Autowired
    private TransferOrderService transferOrderService;

    @Autowired
    private WxPayWalletService wxPayWalletService;

    @Autowired
    private TenantSettingService tenantSettingService;

    /**
     * 企业付款到零钱
     * @param transPayWalletVo 单位为元
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/transPayWallet", method = RequestMethod.POST)
    public TResponse transPayWallet(HttpServletRequest request, @RequestBody WxTransPayWalletVo transPayWalletVo) {
        // 获取当前用户信息
        Subject subject = SecurityUtils.getSubject();
        if (!subject.isAuthenticated()) {//未登录
            return TResponse.FAIL("未登录,操作失败");
        }

        if (StringUtils.isBlank(transPayWalletVo.getRealName())) {
            return TResponse.FAIL("真实姓名不能为空");
        }

        TenantUser tenantUser = (TenantUser) request.getSession().getAttribute(ShiroConstants.SESSION_TENANT_USER_KEY);
        if (tenantUser == null) {
            return TResponse.FAIL("未登录,操作失败");
        }

        MemberInfo memberInfo = memberInfoService.selectMemberByMobile(tenantUser.getTenantCode(), transPayWalletVo.getMobile());
        if (memberInfo == null) {
            return TResponse.FAIL("未登录,操作失败");
        }

        if ("1".equals(memberInfo.getStatus())) {
            return TResponse.FAIL("会员已被冻结");
        }

        long count = transferOrderService.countFailTransferOrderByMember(memberInfo.getMemberId());
        if (count > 0) {
            return TResponse.FAIL("会员还有【" + count + "】笔未付款成功的订单,请稍后再试");
        }

        Tenant tenant = tenantService.selectByPrimaryKey(tenantUser.getTenantCode());

        logger.info("企业付款到零钱,tenantCode:{}:mobile:{},openid:{},realName:{},amount:{}", memberInfo.getTenantCode(), memberInfo.getMobile(),
                memberInfo.getWechatOpenid(), transPayWalletVo.getRealName(), transPayWalletVo.getAmount());

        //检查member_account是否有数据没有则新增
        MemberAccount memberAccount = memberAccountService.selectByPrimaryKey(memberInfo.getMemberId());
        if (memberAccount == null) {
            MemberAccount memberAccountNew = new MemberAccount();
            memberAccountNew.setMemberId(memberInfo.getMemberId());
            memberAccountNew.setTenantCode(tenantUser.getTenantCode());
            memberAccountNew.setCreatedTime(new Date());
            memberAccountService.insertSelective(memberAccountNew);
        }

        TenantSetting tenantSetting = tenantSettingService.selectByPrimaryKey(tenant.getTenantCode());
        if (tenantSetting == null || StringUtils.isBlank(tenantSetting.getWxTransferCertPath())) {
            return TResponse.FAIL("找不到商户证书文件");
        }

        try {
            //1 转帐
            return wxPayWalletService.transPayWallet(request, tenant, memberInfo, transPayWalletVo, tenantSetting);
        } catch (Exception e) {
            logger.error("微信付款异常", e);
            return TResponse.FAIL("转账失败");
        }
    }
}